package Part1_File类;

import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * ClassName: FileTest
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.04.18 22:47
 */
public class FileTest {
    @Test
    public void test1() {
        File file1 = new File("src\\a.txt");//相对路径
        File absoluteFile1 = file1.getAbsoluteFile();
        String path1 = file1.getPath();
        System.out.println(absoluteFile1);
        //D:\My code\Java\JavaSE_Demo13_File\JavaSE_Demo13_File\a.txt

        System.out.println(file1.isFile());
        System.out.println(file1.isDirectory());
        System.out.println(file1.exists());

        System.out.println(file1.length());
        System.out.println(path1);//相对路径

        System.out.println(file1.getName());//a.txt

        String parent = file1.getParent();
        System.out.println(parent);//父类文件夹src

        //D:\My code\Java\JavaSE_Demo13_File\src
        System.out.println(file1.getAbsoluteFile().getParent());
    }

    @Test
    public void test2() {
        File file1 = new File("D:\\My code\\Java\\JavaSE_Demo10_集合");
        String[] list = file1.list();//此目录下的ls
        for (String s : list) {
            System.out.println(s);
        }
        System.out.println();

        File[] files = file1.listFiles();
        for (File fileList : files) {
            System.out.println(fileList + "-->" + fileList.length());
        }
    }

    @Test
    public void test3(){
        //file1必须存在
        //file2必须不存在
        File file1 = new File("a.txt");
        File file2 = new File("src\\hello.txt");

        boolean ifRename = file1.renameTo(file2);
        System.out.println(file1.getAbsoluteFile()+"-->"+(ifRename?"重命名成功":"重命名失败"));

    }

    @Test
    public void test4(){
        File fileDocument = new File("D:\\Sherbledore\\Documents\\代码随想录PDF全集V3.0");
        File[] files = fileDocument.listFiles();
        for(File file : files){
            String oldName = file.getName();
            //操作
        }
    }

    @Test
    public void test5() throws IOException {
        File file1 = new File("D:\\My code\\Java\\JavaSE_Demo13_File\\src\\aa.txt");

        if(!file1.exists()){
            boolean ifSuccessed = file1.createNewFile();//创建
            if(ifSuccessed)
                System.out.println("创建成功");
        }else {
            System.out.println("文件已存在");

            boolean ifDelete = file1.delete();
            if(ifDelete)
                System.out.println("文件已删除");

        }
    }

    @Test
    public void test6() {
        File file1 = new File("D:\\My code\\Java\\JavaSE_Demo13_File\\src\\dir1");
        //mkdir()：上级菜单必须存在，才能创建dir1
        System.out.println(file1.mkdir());

        //mkdirs()：上级菜单不存在，也能创建
        File file2 = new File("D:\\My code\\Java\\JavaSE_Demo13_File\\src\\dir2\\dir3");
        System.out.println(file2.mkdirs());

        if(file2.exists())
            System.out.println(""+file2.delete());
    }
}
